package com.xxl.sso.server.controller;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.icom.sso.util.RetKit;
import com.xxl.sso.core.entity.PageData;
import com.xxl.sso.core.login.SsoWebLoginHelper;
import com.xxl.sso.core.user.XxlSsoUser;
import com.xxl.sso.server.core.model.BackTree;
import com.xxl.sso.server.core.model.Department;
import com.xxl.sso.server.core.model.SysUser;
import com.xxl.sso.server.service.DepartmentService;
import com.xxl.sso.server.service.SysUserService;

@Controller
@RequestMapping("/dept")
public class DepartmentController {
	@Autowired
	private DepartmentService departmentService;
	@Autowired
	private SysUserService sysUserService;

	@RequestMapping("/page")
	public String page() {
		return "department/department_list";
	}

	@RequestMapping("/findDept")
	@ResponseBody
	public PageData<Department> findDept(@RequestParam(defaultValue = "1") Integer page,
			@RequestParam(defaultValue = "10") Integer rows, String dptId, String name, String no) {
		if (dptId == null || "10000".equals(dptId.trim())) {
			PageData<Department> result = departmentService.pageFindDept(page, rows, null, name, no);
			return result;
		} else {
			PageData<Department> result = departmentService.pageFindDept(page, rows, dptId, name, no);
			return result;
		}
	}

	/**
	 * 获取部门信息树
	 * 
	 * @return
	 */
	@RequestMapping("/getTree")
	@ResponseBody
	public List<BackTree> getTrees() {

		List<BackTree> list = departmentService.findDeptTree();
		// 为部门树列表设置图标，根据层级设置不同的图标
		for (BackTree record : list) {
			if (record.getParent() == 0) {
				record.setParent(10000);
			}

			if ("1".equals(record.getLevel())) {
				record.setIcon("fa fa-home");
			} else if ("2".equals(record.getLevel())) {
				record.setIcon("fa fa-flag");
			} else if ("3".equals(record.getLevel())) {
				record.setIcon("fa fa-cube");
			}
		}

		// 设置根节点
		BackTree root = new BackTree();
		root.setId(10000);
		root.setText("全部");
		root.setParent(0);
		root.setIcon("fa fa-map-o");

		list.add(root);
		return list;
	}

	@RequestMapping("/check")
	@ResponseBody
	public RetKit<String> checkDept(HttpServletRequest request, HttpServletResponse response) {
		RetKit<String> ret = new RetKit<String>(null);
		String id = request.getParameter("id");

		ret = checkInfo(id);

		return ret;
	}

	@RequestMapping("/addDept")
	public String addDept(Model model, HttpServletRequest request, HttpServletResponse response) {
		String deptId = request.getParameter("deptId");
		if (deptId == null || deptId.trim() == "") {
			model.addAttribute("pid", "0");
		} else {
			Department department = departmentService.findDeptById(deptId);
			model.addAttribute("dept", department);
		}

		return "department/department_add";
	}

	@RequestMapping("/saveDept")
	@ResponseBody
	public RetKit<String> saveDept(HttpServletRequest request, HttpServletResponse response, Department department,
			String top_level) {
		RetKit<String> ret = new RetKit<String>(null);
		ret.setSuccess();

		// SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date date = new Date();

		// 获取当前登录用户
		XxlSsoUser xxlUser = SsoWebLoginHelper.loginCheck(request, response);
		SysUser user = sysUserService.findUserByLoginId(xxlUser.getLoginid());

		if (department.getName() == null || department.getName() == "") {
			ret.setFail();
			ret.setMsg("部门名称不能为空！");
			return ret;
		} else if (department.getDeptNo() == null || department.getDeptNo() == "") {
			ret.setFail();
			ret.setMsg("部门编号不能为空！");
			return ret;
		}
		
		//校验数据
		ret = this.checkInfo(String.valueOf(department.getPid()));
		if (!ret.getFlag()) {
			return ret;
		}

		if (top_level == null || top_level.trim() == "") {
			department.setLevel("1");
		} else {
			department.setLevel(String.valueOf((Integer.valueOf(top_level) + 1)));
		}

		// 设置字段
		department.setCreatedby(user.getId());
		department.setCreatedon(date);
		department.setModifiedby(user.getId());
		department.setModifiedon(date);

		ret = departmentService.saveDept(department);

		return ret;
	}

	@RequestMapping("/editInfo")
	public String editDeptInfo(Model model, HttpServletRequest request, HttpServletResponse response) {
		String id = request.getParameter("id");
		Department department = departmentService.findDeptById(id);

		Department topDept = departmentService.findDeptById(String.valueOf(department.getPid()));
		model.addAttribute("dept", department);
		model.addAttribute("topDept", topDept);
		return "department/department_edit";
	}

	/**
	 * 保存部门信息修改
	 * 
	 * @param department
	 * @return
	 */
	@RequestMapping("/saveEditInfo")
	@ResponseBody
	public RetKit<String> saveEditInfo(Department department) {
		RetKit<String> ret = new RetKit<String>(null);
		// 部门信息修改只需要修改名称
		if (department.getId() == 0) {
			ret.setFail();
			ret.setMsg("修改部门信息出现错误");
			return ret;
		} else if (department.getName() == null || department.getName().trim() == "") {
			ret.setFail();
			ret.setMsg("部门名称不能为空");
			return ret;
		}

		ret = departmentService.saveEditInfo(department);

		return ret;
	}

	/**
	 * 删除部门，使用的是标志位删除，status ： 0 表示删除
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/delDept")
	@ResponseBody
	public RetKit<String> delDept(HttpServletRequest request, HttpServletResponse response) {
		RetKit<String> ret = new RetKit<String>(null);

		String id = request.getParameter("id");

		if (id == null || id.trim() == "") {
			ret.setFail();
			ret.setMsg("删除部门出现错误！");
			return ret;
		}
		ret = departmentService.delDept(id);

		return ret;
	}

	private RetKit<String> checkInfo(String id) {
		RetKit<String> ret = new RetKit<String>(null);
		if (id == null || id.trim() == "") {
			ret.setSuccess();
			return ret;
		}

		Department department = departmentService.findDeptById(id);
		if (department == null) {
			ret.setFail();
			ret.setMsg("新增部门出现错误！");
			return ret;
		}

		if ("1".equals(department.getIsLast())) {
			ret.setFail();
			ret.setMsg(department.getName() + "，部门为底级部门，不能新增下级部门！");
			return ret;
		}

		ret.setSuccess();
		return ret;
	}
}
